import { defineStore } from 'pinia';
import { ref } from 'vue';
import { UserInfoState } from './interface';
// 用户store
export const userInfoStore = defineStore('userInfo', () => {
	//用户信息
	const userInfo = ref<UserInfoState>(
		uni.getStorageSync('dx_user_info') || {
			role: [],
			permission: [],
			_id: '',
			avatar: '',
			mobile: '',
			email: '',
			nickname: '',
			username: '',
			gender: 0,
			tokenExpired: 0,
		}
	);
	// 是否登录
	const isLogin = ref(userInfo.value.tokenExpired - Date.now() > 0);
	// 设置用户信息
	const setUserInfo = (info: any) => {
		userInfo.value = info;
		isLogin.value = true;
		uni.setStorageSync('dx_user_info', info);
		uni.setStorageSync('uni_id_token', info.token);
		uni.setStorageSync('uni_id_token_expired', info.tokenExpired);
	};
	// 权限判断
	const hasPermission = (value: any) => {
		const permission: string[] = userInfo.value.permission;
		let status = false;
		// 如果是超级管理员，直接显示
		if (userInfo.value.role.includes('admin')) {
			status = true;
		} else {
			if (typeof value === 'string') {
				status = permission.includes(value);
			} else if (Array.isArray(value)) {
				status = value.some((item) => permission.includes(item));
			}
		}
		return status;
	};	
	// 退出登录
	const logout = () => {
		isLogin.value = false;
		uni.clearStorageSync();
	};
	// 判断是否登录
	const checkLogin = () => {
		if (userInfo.value.tokenExpired - Date.now() <= 0) {
			logout();
		} else {
			isLogin.value = true;
		}
		// 10分钟内，还在操作，自动刷新token,
		return userInfo.value.tokenExpired - Date.now() <= 600000 && userInfo.value.tokenExpired - Date.now() > 0;
	};

	return {
		isLogin,
		checkLogin,
		userInfo,
		setUserInfo,
		hasPermission,
	};
});
